package com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.persenter;

import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.anew.journey.mynewjourney.R;
import com.example.anew.journey.mynewjourney.base.MyApplication;
import com.example.anew.journey.mynewjourney.bean.TakeDateBean;
import com.example.anew.journey.mynewjourney.config.RBConstants;
import com.example.anew.journey.mynewjourney.customview.MyRecyclerView;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.adpater.DevicesListAdapter;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.bean.BadingDevicesBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.bean.DevicesBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.bean.MainDevices;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.bean.verifyBindingBean;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.model.FirstChangeDevicesModel;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.model.ISFirstChangeDevicesModel;
import com.example.anew.journey.mynewjourney.firstchangelogic.FirstChangeDevices.view.ISFirstChangeDevicesView;
import com.example.anew.journey.mynewjourney.firstchangelogic.firstChangeAddDevices.FirstChangeAddDevicesActvity;
import com.example.anew.journey.mynewjourney.firstchangelogic.frstChangeSecondTimeCardiacDetection.FrstChangeSecondTimeCardiacDetectionActivity;
import com.example.anew.journey.mynewjourney.inteface.OnRecyclerViewItemClickListener;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 杭州惟君医疗科技有限公司15
 * Created by 20433 on 2018/3/15
 */

public class FirstChangeDevicesPersenter {
    private ISFirstChangeDevicesView mISFirstChangeDevicesView;
    private ISFirstChangeDevicesModel mISFirstChangeDevicesModel;

    private int p = 1;
    private DevicesListAdapter mDevicesListAdapter;
    MyRecyclerView mactivityFirstChangeDevicesMyRecyclerview;
    private  SimpleDateFormat formatter;
    private RelativeLayout mrl_error_pager;

    public FirstChangeDevicesPersenter(ISFirstChangeDevicesView iSFirstChangeDevicesView) {
        this.mISFirstChangeDevicesView = iSFirstChangeDevicesView;
        mISFirstChangeDevicesModel = new FirstChangeDevicesModel();
          formatter = new SimpleDateFormat("yyyy-MM-dd");

    }

    // 初始化设备列表数据
    public void initDevicesList(MyRecyclerView activityFirstChangeDevicesMyRecyclerview, final Context mcontxt, int device_page_identification,RelativeLayout rl_error_pager) {
        mactivityFirstChangeDevicesMyRecyclerview = activityFirstChangeDevicesMyRecyclerview;
        mrl_error_pager = rl_error_pager;
        LinearLayoutManager layoutManager = new LinearLayoutManager(mcontxt);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        activityFirstChangeDevicesMyRecyclerview.setLayoutManager(layoutManager);
        activityFirstChangeDevicesMyRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        activityFirstChangeDevicesMyRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        activityFirstChangeDevicesMyRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        activityFirstChangeDevicesMyRecyclerview.setPullRefreshEnabled(false);  //TODO 禁止下拉刷新完毕
        activityFirstChangeDevicesMyRecyclerview.getDefaultFootView().setNoMoreHint("就这么多了");
        // TODO 传入数据
        mDevicesListAdapter = new DevicesListAdapter(mcontxt);
        activityFirstChangeDevicesMyRecyclerview.setAdapter(mDevicesListAdapter);
        activityFirstChangeDevicesMyRecyclerview.refresh();

        if (device_page_identification == 0) { //侧边栏设备
            loadDevicesDate(activityFirstChangeDevicesMyRecyclerview, mcontxt,rl_error_pager);
        } else if (device_page_identification == 1) { //主页点击设备
            p = 1;
            loadMainDevicesDate(activityFirstChangeDevicesMyRecyclerview, mcontxt,rl_error_pager);

        }

    }

    @Nullable
    public TakeDateBean getMyuserID(Context mcontxt) {
        TakeDateBean bean = mISFirstChangeDevicesModel.TakeDate(mcontxt);
        if (bean == null) return null;
        return bean;
    }

    // todo  FloatingActionButton 点击跳转的页面
    public void loadMainDevicesDate(final MyRecyclerView activityFirstChangeDevicesMyRecyclerview, final Context mcontxt, final RelativeLayout rl_error_pager) {
        String url = RBConstants.SERVER_URL + RBConstants.MY_MAIN_DEVICES;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", getMyuserID(mcontxt).getUser_id())
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                       // NLogger.e("TAG", "===main========点击跳转的页面=NetworkResponseDate=================" + NetworkResponseDate);
                        final MainDevices mainDevices = gson.fromJson(NetworkResponseDate, MainDevices.class);
                        if (mainDevices.errorCode == 200) {
                            mDevicesListAdapter.clearItem();
                            final List<MainDevices.DataBean> beanlist = mainDevices.data;
                            if (beanlist != null) {
                                if(beanlist.size() == 0){
                                    MyApplication.getmHandler().post(new Runnable() {
                                        @Override
                                        public void run() {
                                            rl_error_pager.setVisibility(View.VISIBLE);
                                           // NLogger.e("TAG", "==========加载侧边栏======322=============" );
                                        }
                                    });
                                }
                                final List<DevicesBean> mdatelist = mainDataConversion(beanlist);
                                mainFitData(mdatelist, activityFirstChangeDevicesMyRecyclerview, mcontxt);
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                       // mISFirstChangeDevicesView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    private void mainFitData(final List<DevicesBean> mdatelist, final MyRecyclerView activityFirstChangeDevicesMyRecyclerview, final Context mcontxt) {
        MyApplication.getmHandler().post(new Runnable() {
            @Override
            public void run() {
                mDevicesListAdapter.addDate(mdatelist);
                mDevicesListAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view) {
                        int postion = activityFirstChangeDevicesMyRecyclerview.getChildAdapterPosition(view) - 1;
                        String binding = mdatelist.get(postion).binding;
                        if (binding == null ||binding.equals("null")) {
                            Intent intent = new Intent(mcontxt, FirstChangeAddDevicesActvity.class);
                            intent.putExtra("devices_id", mdatelist.get(postion).id);
                            intent.putExtra("Page_identification_code", 1);
                            mcontxt.startActivity(intent);
                        } else {

                           /* if(formatter.format(new Date()).equals(mISFirstChangeDevicesModel.TakeISFirstDate(mcontxt).datestr)){
                                Intent intent = new Intent(mcontxt, FrstChangeSecondTimeCardiacDetectionActivity.class);
                                intent.putExtra("devices_name",mdatelist.get(postion).binding);
                                mcontxt.startActivity(intent);
                            }else{
                                Intent intent = new Intent(mcontxt, FirstChangeCardiacDetectionActivity.class);
                                intent.putExtra("devices_name",mdatelist.get(postion).binding);
                                mcontxt.startActivity(intent);
                            }*/
                            Intent intent = new Intent(mcontxt, FrstChangeSecondTimeCardiacDetectionActivity.class);
                            intent.putExtra("devices_name",mdatelist.get(postion).binding);
                            mcontxt.startActivity(intent);
                        }
                    }

                    @Override
                    public void onItemFirstButtonClick(View v, int position) {
                        String binding = mdatelist.get(position).binding;
                        if(binding == null){
                            Intent intent = new Intent(mcontxt, FirstChangeAddDevicesActvity.class);
                            intent.putExtra("devices_id", mdatelist.get(position).id);
                            intent.putExtra("Page_identification_code", 1);
                            mcontxt.startActivity(intent);
                        }else{
                            //todo 弹出对话框
                            mISFirstChangeDevicesView.showRemoveBinding(mdatelist.get(position).id,mdatelist.get(position).getType());
                        }

                    }
                });
            }
        });
    }

    @NonNull
    private List<DevicesBean> mainDataConversion(List<MainDevices.DataBean> beanlist) {
        final List<DevicesBean> mdatelist = new ArrayList<DevicesBean>();
        for (MainDevices.DataBean dataBean : beanlist) {
            DevicesBean bean = new DevicesBean();
            bean.setId(dataBean.goods_id);
            bean.setBinding(dataBean.binding);
            bean.setName(dataBean.name);
            bean.setUrl(dataBean.url);
            bean.setType(0);
            mdatelist.add(bean);
        }
        return mdatelist;
    }

    // todo  加载侧边栏  设备列表数据
    public void loadDevicesDate(final MyRecyclerView activityFirstChangeDevicesMyRecyclerview, final Context mcontxt, final RelativeLayout rl_error_pager) {
        String url = RBConstants.SERVER_URL + RBConstants.MY_MAIN_DEVICES;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", getMyuserID(mcontxt).getUser_id())
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                      // NLogger.e("TAG", "==========加载侧边栏==NetworkResponseDate=================" + NetworkResponseDate);
                        final BadingDevicesBean badingDevicesBean = gson.fromJson(NetworkResponseDate, BadingDevicesBean.class);
                        if (badingDevicesBean.errorCode == 200) {
                            mDevicesListAdapter.clearItem();
                            final List<BadingDevicesBean.DataBean> beanlist = badingDevicesBean.data;
                            if (beanlist != null ) {
                                if(beanlist.size() == 0){
                                    MyApplication.getmHandler().post(new Runnable() {
                                        @Override
                                        public void run() {
                                            rl_error_pager.setVisibility(View.VISIBLE);
                                          //  NLogger.e("TAG", "==========加载侧边栏======322=============" );
                                        }
                                    });

                                }
                                final List<DevicesBean> mdatelist = dataConversion(beanlist);
                                FitData( mdatelist, activityFirstChangeDevicesMyRecyclerview, mcontxt);
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {}
                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });


    }

    private void FitData(final List<DevicesBean> mdatelist, final MyRecyclerView activityFirstChangeDevicesMyRecyclerview, final Context mcontxt) {
        MyApplication.getmHandler().post(new Runnable() {
            @Override
            public void run() {
                mDevicesListAdapter.addDate(mdatelist);
                mDevicesListAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view) {
                       int postion =  activityFirstChangeDevicesMyRecyclerview.getChildAdapterPosition(view)-1;
                       String binding =  mdatelist.get(postion).binding;
                        if(binding == null || binding.equals("null")){
                            Intent intent = new Intent(mcontxt, FirstChangeAddDevicesActvity.class);
                            intent.putExtra("devices_id", mdatelist.get(postion).id);
                            intent.putExtra("Page_identification_code", 1);
                            mcontxt.startActivity(intent);
                        }else{
//                            if(formatter.format(new Date()).equals(mISFirstChangeDevicesModel.TakeISFirstDate(mcontxt).datestr)){
//                                Intent intent = new Intent(mcontxt, FrstChangeSecondTimeCardiacDetectionActivity.class);
//                                intent.putExtra("devices_name",mdatelist.get(postion).binding);
//                                mcontxt.startActivity(intent);
//                            }else{
//
//                                Intent intent = new Intent(mcontxt, FirstChangeCardiacDetectionActivity.class);
//                                intent.putExtra("devices_name",mdatelist.get(postion).binding);
//                                mcontxt.startActivity(intent);
//                            }
                            Intent intent = new Intent(mcontxt, FrstChangeSecondTimeCardiacDetectionActivity.class);
                            intent.putExtra("devices_name",mdatelist.get(postion).binding);
                            mcontxt.startActivity(intent);
                        }

                    }
                    @Override
                    public void onItemFirstButtonClick(View v, int position) {
                       TextView tv = (TextView) v;
                        if(tv.getText().toString().contains("解除绑定")){
                            //todo 弹出对话框
                            mISFirstChangeDevicesView.showRemoveBinding(mdatelist.get(position).id,mdatelist.get(position).getType());
                        }else{
                            Intent intent = new Intent(mcontxt, FirstChangeAddDevicesActvity.class);
                            intent.putExtra("devices_id", mdatelist.get(position).id);
                            intent.putExtra("Page_identification_code", 1);
                            mcontxt.startActivity(intent);
                        }
                    }
                });
            }
        });
    }

    @NonNull
    private List<DevicesBean> dataConversion(List<BadingDevicesBean.DataBean> beanlist) {
        final List<DevicesBean> mdatelist = new ArrayList<DevicesBean>();
        for (BadingDevicesBean.DataBean dataBean : beanlist) {
            DevicesBean bean = new DevicesBean();
            bean.setId(dataBean.goods_id);
            bean.setBinding(dataBean.binding);
            bean.setName(dataBean.name);
            bean.setUrl(dataBean.url);
            bean.setType(1);
            mdatelist.add(bean);
        }
        return mdatelist;
    }
    //   我在想想
    public void verifyBindingFailedIThink(){
        mISFirstChangeDevicesView.removeBindingIThink();
    }
    //确认解绑
    public void verifyBindingFailedConfirmUnbundling(String devices_id, final Context mcontxt, final int type){

        String url = RBConstants.SERVER_URL + RBConstants.REMOVE_BANDING_DEVICES;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("cus_id", getMyuserID(mcontxt).getUser_id())
                .addParams("goods_id", devices_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String NetworkResponseDate = response.body().string();
                        Gson gson = new Gson();
                         //NLogger.e("TAG", "============NetworkResponseDate=================" + NetworkResponseDate);
                        final verifyBindingBean mverifyBindingBean =   gson.fromJson(NetworkResponseDate, verifyBindingBean.class);
                        MyApplication.getmHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if(mverifyBindingBean.errorCode == 200 ){
                                    if(type == 0){
                                        loadMainDevicesDate(mactivityFirstChangeDevicesMyRecyclerview, mcontxt,mrl_error_pager);
                                    }else  if(type == 1){
                                        loadDevicesDate(mactivityFirstChangeDevicesMyRecyclerview, mcontxt,mrl_error_pager);
                                    }

                                    mISFirstChangeDevicesView.showToastInformation("解除绑定成功");
                                }else{
                                    mISFirstChangeDevicesView.showToastInformation("解除绑定失败");
                                }
                                verifyBindingFailedIThink();
                            }
                        });
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        verifyBindingFailedIThink();
                       // mISFirstChangeDevicesView.showToastInformation("请查看网络");
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
}
